﻿#include <QHttpMultiPart>
#include <QHttpPart>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QCoreApplication>
#include "CSensorSeriesOper.h"
#include "CGlobal.h"
#include "CLogOper.h"
#include "CIsapiClient.h"
#include "CIsapiServer.h"
#include "CSqlOper.h"
#include "Public.h"
#include "CGlobal.h"

CSensorSeriesOper::CSensorSeriesOper(CDevDataSensorSeries* pDevData)
{
	m_pDevData = pDevData;
	m_pIsapiClient = new CIsapiClient(m_pDevData->m_sUserName, m_pDevData->m_sPassWd);
	// 如果当前不在主线程，将 CIsapiClient 移动到主线程
	if (this->thread() != QCoreApplication::instance()->thread())
	{
		m_pIsapiClient->moveToThread(QCoreApplication::instance()->thread());
	}
	qRegisterMetaType<SRequestResult>("SRequestResult");
	connect(m_pIsapiClient, &CIsapiClient::sigResult, this, &CSensorSeriesOper::slotResult);
	connect(m_pIsapiClient, &CIsapiClient::sigResultParam, this, &CSensorSeriesOper::slotResultParame);

	// 连接内部请求信号 - 使用 QueuedConnection 确保跨线程安全
	connect(this, &CSensorSeriesOper::sigInternalPostRequest,
		this, &CSensorSeriesOper::handleInternalPostRequest, Qt::QueuedConnection);
	connect(this, &CSensorSeriesOper::sigInternalGetRequest,
		this, &CSensorSeriesOper::handleInternalGetRequest, Qt::QueuedConnection);
	connect(this, &CSensorSeriesOper::sigInternalGetRequestWithParam,
		this, &CSensorSeriesOper::handleInternalGetRequestWithParam, Qt::QueuedConnection);
}

CSensorSeriesOper::~CSensorSeriesOper()
{
	if (m_pIsapiClient != nullptr)
	{
		delete m_pIsapiClient;
		m_pIsapiClient = nullptr;
	}
}

bool CSensorSeriesOper::CtrDevice(SCtrInfo& stCtrInfo)
{
	int nCmd = stCtrInfo.m_nCtrCmd;
	bool bResult = false;
	SExecLog ExecLog;
	ExecLog.m_sDevName = m_pDevData->m_sDevName;
	ExecLog.m_sFuncName = A2T("请求数据");
	switch (nCmd)
	{
	case ERequestType::enSearchHistoryData:
		bResult = searchHistoryData(stCtrInfo);
		break;
	case ERequestType::enGetSensorCollectDataFile:
		bResult = getSensorCollectDataFile(stCtrInfo);
		break;
	default:
	{
		bResult = true;
	}
	break;
	}
	ExecLog.m_sDescriptionl = stCtrInfo.m_sReData;
	if (bResult)
	{
		ExecLog.m_nAlarmLevel = enWorkInfo;
	}
	else
	{
		ExecLog.m_nAlarmLevel = enDevAlarm;
	}
	CLogOper::instance().addMsg(ExecLog);
	m_nCtrCmdCurr = -1;  //清空命令
	return bResult;
}

bool CSensorSeriesOper::GetDevState()
{
	QString sUrl = QString("http://") + m_pDevData->m_sIp + "/ISAPI/IoTGateway/Childmanage/SearchChild?format=json";
	QUrl url(sUrl);
	QByteArray postData;
	postData.append("\{\"pageSize\":100,\"\pageIndex\":1}");
	//m_pIsapiClient->sendRequestPost(ERequestType::enSearchChild,url, postData);
	// 通过信号发送请求，确保在正确的线程执行
	emit sigInternalPostRequest(ERequestType::enSearchChild, url, postData);
	return true;
}

bool CSensorSeriesOper::GetHistoryData(QString sStartTime, QString sEndTime)
{
	QString sUrl = QString("http://") + m_pDevData->m_sIp + "/ISAPI/Intelligent/AIOpenPlatform/audioDetectionSearch?format=json";
	QUrl url(sUrl);
	QByteArray postData;
	// 创建SearchDescription对象
	QJsonObject searchDescription;
	searchDescription["searchID"] =createGuid();
	searchDescription["searchResultPosition"] = 0;
	searchDescription["maxResults"] = 1000;
	searchDescription["startTime"] = sStartTime;
	searchDescription["endTime"] = sEndTime;
	searchDescription["result"] = "all";
	searchDescription["maxResultNumber"] = 10000;

	// 创建audioList数组
	QJsonArray audioList;
	for (int i = 1; i <= 8; ++i)
	{
		QJsonObject audioObject;
		audioObject["audioID"] = i;

		// 创建accDirect数组
		QJsonArray accDirect;
		accDirect.append("x");
		accDirect.append("y");
		accDirect.append("z");

		audioObject["accDirect"] = accDirect;

		// 添加audio对象到audioList数组
		audioList.append(audioObject);
	}
	// 将audioList添加到searchDescription中
	searchDescription["audioList"] = audioList;
	// 创建JSON对象
	QJsonObject jsonObject;
	jsonObject["SearchDescription"] = searchDescription;
	QJsonDocument doc(jsonObject);// 将 JSON 对象转换为字符串
	postData = doc.toJson();
	//m_pIsapiClient->sendRequestPost(ERequestType::enSyncHistoryData, url, postData);
	emit sigInternalPostRequest(ERequestType::enSyncHistoryData, url, postData);
	return true;
}

void CSensorSeriesOper::analySearchChild(SRequestResult stRequestResult)
{
	if (stRequestResult.bResult == false)//请求失败
	{
		m_pDevData->m_pMutex->lock();
		m_pDevData->m_nState = 0;//算法仓离线
		m_pDevData->m_nStateValue = 0;//算法仓离线
		m_pDevData->m_pMutex->unlock();
	}
	else
	{
		m_pDevData->m_pMutex->lock();
		m_pDevData->m_nState = 1;//算法仓在线
		m_pDevData->m_nStateValue = 1;//算法仓在线
		m_pDevData->m_pMutex->unlock();
		/*{
			"pageCount":	1,
				"totalMatches" : 8,
				"childList" : [{
				"connected":	true,
					"childDevID" : "1",
					"serialNumber" : "FR6242321",
					"version" : "V1.1.0build20240722",
					"model" : "DS-ASS301",
					"childStatus" : "connect",
					"tags" : [{
					"Key":	"bearingModel",
						"Value" : "OTHERS"
				}, {
					"Key":	"motorClass",
					"Value" : 0
				}, {
					"Key":	"speedDetect",
					"Value" : "false"
				}, {
					"Key":	"childDescription",
					"Value" : "通道1"
				}, {
					"Key":	"sensorType",
					"Value" : "MEMS"
				}, {
					"Key":	"remark",
					"Value" : ""
				}]
			}, {
				"connected":	false,
				"childDevID" : "2",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道2"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "3",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道3"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "4",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道4"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "5",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道5"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "6",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道6"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "7",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道7"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}, {
				"connected":	false,
				"childDevID" : "8",
				"serialNumber" : "",
				"version" : "",
				"model" : "",
				"childStatus" : "unbound",
				"tags" : [{
						"Key":	"bearingModel",
						"Value" : "OTHERS"
					}, {
						"Key":	"motorClass",
						"Value" : 0
					}, {
						"Key":	"speedDetect",
						"Value" : "false"
					}, {
						"Key":	"childDescription",
						"Value" : "通道8"
					}, {
						"Key":	"sensorType",
						"Value" : "IEPE"
					}, {
						"Key":	"remark",
						"Value" : ""
					}]
			}]
		}*/
		//解析json
		QString sResult = QString::fromLocal8Bit(stRequestResult.sResult);
		QJsonDocument doc= QJsonDocument::fromJson(sResult.toLocal8Bit());
		if (!doc.isNull())
		{
			QJsonObject rootObj = doc.object();
			// 获取 "childList" 数组
			if (rootObj.contains("childList"))
			{
				QJsonArray childList = rootObj["childList"].toArray();

				// 遍历 childList 数组，提取信息
				for (const QJsonValue &value : childList)
				{
					QJsonObject childObj = value.toObject();
					if (childObj.contains("childDevID"))
					{
						int nChildDevId = childObj["childDevID"].toString().toInt();
						m_pDevData->m_pMutex->lock();
						if (m_pDevData->m_mapChannel.contains(nChildDevId))
						{
							if (childObj.contains("connected"))
							{
								m_pDevData->m_mapChannel[nChildDevId].nState = childObj["connected"].toBool();
								m_pDevData->m_mapChannel[nChildDevId].nStateValue = childObj["connected"].toBool();
							}
							if (childObj.contains("serialNumber"))
							{
								m_pDevData->m_mapChannel[nChildDevId].sSerialNumber = childObj["serialNumber"].toString();
							}

						}
						m_pDevData->m_pMutex->unlock();
					}
				}
			}
		}
	}
}

bool CSensorSeriesOper::searchHistoryData(SCtrInfo& stCtrInfo)
{
	QString sUrl = QString("http://") + m_pDevData->m_sIp + "/ISAPI/IoTGateway/MultiSenseDataMgr/SearchHistorySensorData?format=json";
	QUrl url(sUrl);
	QByteArray postData;
	QJsonObject json;
	json["searchID"] =createGuid();// 设置 searchID
	json["searchResultPosition"] = 0;// 设置 searchResultPosition
	json["maxResults"] = 50000;// 设置 maxResults
	json["sensorType"] = "list";// 设置 sensorType
	// 创建 childDevList 数组
	QJsonArray childDevList;
	QJsonObject childDev;
	childDev["childDevID"] = stCtrInfo.m_pCtrSensorSeriesInfo->nChannel;
	childDevList.append(childDev);
	json["childDevList"] = childDevList;
	json["senseType"] = "all";// 设置 senseType
	// 创建 timeRange 对象
	QJsonObject timeRange;
	timeRange["beginTime"] = stCtrInfo.m_pCtrSensorSeriesInfo->szStartTime;
	timeRange["endTime"] = stCtrInfo.m_pCtrSensorSeriesInfo->szEndTime;
	json["timeRange"] = timeRange;
	// 设置 dataDirection
	if (stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 1)
	{
		json["dataDirection"] = "x";
	}
	else if (stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 2)
	{
		json["dataDirection"] = "y";
	}
	else if(stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 3)
	{
		json["dataDirection"] = "z";
	}
	else
	{
		json["dataDirection"] = "z";//默认查z轴
	}
	QJsonDocument doc(json);// 将 JSON 对象转换为字符串
	postData = doc.toJson();
	//m_pIsapiClient->sendRequestPost(ERequestType::enSearchHistoryData, url, postData);
	emit sigInternalPostRequest(ERequestType::enSearchHistoryData, url, postData);
	stCtrInfo.m_sReData = A2T("下发查询历史曲线命令");
	return true;
}

void CSensorSeriesOper::analyHisAccelerationFile(SRequestResult stRequestResult, QString sPath)
{
	QString sData = QString::fromLocal8Bit(stRequestResult.sResult);
	QFileInfo fileInfo(sPath);
	QString dirPath = fileInfo.absoluteDir().absolutePath();
	// 检查文件夹是否存在
	QDir dir;
	if (!dir.exists(dirPath))
	{
		// 如果文件夹不存在，则创建它
		if (!dir.mkpath(dirPath)) 
		{
			return;
		}
	}
	// 打开文件
	QFile file(sPath);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		return;
	}

	// 使用 QTextStream 来写入文本
	QTextStream out(&file);
	out << sData;
	// 关闭文件
	file.close();
}

void CSensorSeriesOper::analyHisAudioFile(SRequestResult stRequestResult, QString sPath)
{
	QFileInfo fileInfo(sPath);
	QString dirPath = fileInfo.absoluteDir().absolutePath();
	// 检查文件夹是否存在
	QDir dir;
	if (!dir.exists(dirPath))
	{
		// 如果文件夹不存在，则创建它
		if (!dir.mkpath(dirPath))
		{
			return;
		}
	}
	// 打开文件
	QFile file(sPath);
	if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
	{
		return;
	}

	// 使用 QTextStream 来写入文本
	QTextStream out(&file);
	out << stRequestResult.sResult;
	// 关闭文件
	file.close();
}

void CSensorSeriesOper::analyHistoryData(SRequestResult stRequestResult)
{
	emit(m_pDevData->sigResult(enSearchHistoryData, QString::fromLocal8Bit(stRequestResult.sResult)));
}

bool CSensorSeriesOper::getSensorCollectDataFile(SCtrInfo& stCtrInfo)
{
	QString sUrl = QString("http://") + m_pDevData->m_sIp + "/ISAPI/IoTGateway/MultiSenseDataMgr/GetSensorCollectDataFile?format=json";
	QUrl url(sUrl);
	QByteArray postData;
	// 创建 JSON 对象
	QJsonObject rootObject;
	// 创建子设备列表
	QJsonArray childDevList;
	QJsonObject childDevObject;
	childDevObject["childDevID"] = stCtrInfo.m_pCtrSensorSeriesInfo->nChannel;  // 添加 childDevID
	childDevList.append(childDevObject);  // 将子设备添加到数组

	// 设置 beginTime 字段
	QString beginTime = stCtrInfo.m_pCtrSensorSeriesInfo->szStartTime;
	// 设置 dataDirection 字段
	QString dataDirection = "";
	if (stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 1)
	{
		dataDirection = "x";
	}
	else if (stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 2)
	{
		dataDirection = "y";
	}
	else if (stCtrInfo.m_pCtrSensorSeriesInfo->nDataDirection == 3)
	{
		dataDirection = "z";
	}
	// 将子设备列表、beginTime 和 dataDirection 添加到 rootObject
	rootObject["childDevList"] = childDevList;
	rootObject["beginTime"] = beginTime;
	rootObject["dataDirection"] = dataDirection;

	// 创建 QJsonDocument 来构建最终的 JSON 数据
	QJsonDocument doc(rootObject);
	postData = doc.toJson();
	//m_pIsapiClient->sendRequestPost(ERequestType::enGetSensorCollectDataFile, url, postData);
	emit sigInternalPostRequest(ERequestType::enGetSensorCollectDataFile, url, postData);
	stCtrInfo.m_sReData = A2T("下发查询趋势图节点数据命令");
	return true;
}

void CSensorSeriesOper::analyGetSensorCollectDataFile(SRequestResult stRequestResult)
{
	QString sResult = QString::fromLocal8Bit(stRequestResult.sResult);
	QString sAudioFile = "";
	QString sAccelerationFile = "";
	QJsonDocument jsonDoc = QJsonDocument::fromJson(sResult.toLocal8Bit());
	if (!jsonDoc.isNull()) 
	{
		// 获取根对象
		QJsonObject jsonObj = jsonDoc.object();
		// 获取 "dataFileList" 数组
		if (jsonObj.contains("dataFileList"))
		{
			QJsonArray dataFileList = jsonObj["dataFileList"].toArray();
			// 遍历数组
			for (int i = 0; i < dataFileList.size(); ++i)
			{
				QJsonObject item = dataFileList[i].toObject();
				if (item["collectDataType"].toString() == "audio")
				{
					sAudioFile= item["filePath"].toString();
				}
				else if (item["collectDataType"].toString() == "acceleration")
				{
					sAccelerationFile = item["filePath"].toString();
				}
			}
		}
	}
	if (sAccelerationFile.size() > 0)
	{
		getAccelerationFile(sAccelerationFile);
	}
	sysSleep(50);
	if (sAudioFile.size() > 0)
	{
		getAudioFile(sAudioFile);
	}
}

bool CSensorSeriesOper::getAccelerationFile(QString sUrl)
{
	QUrl url(sUrl);
	//m_pIsapiClient->sendRequestGet(ERequestType::enGetAcceleration, url);
	emit sigInternalGetRequest(ERequestType::enGetAcceleration, url);
	return true;
}

void CSensorSeriesOper::analyAccelerationFile(SRequestResult stRequestResult)
{
	emit(m_pDevData->sigResult(enGetAcceleration, QString::fromLocal8Bit(stRequestResult.sResult)));
}

bool CSensorSeriesOper::getAudioFile(QString sUrl)
{
	QUrl url(sUrl);
	//m_pIsapiClient->sendRequestGet(ERequestType::enGetAudio, url);
	emit sigInternalGetRequest(ERequestType::enGetAudio, url);
	return true;
}

void CSensorSeriesOper::analyAudioFile(SRequestResult stRequestResult)
{
	emit(m_pDevData->sigResult(enGetAudio, stRequestResult.sResult));
}

void CSensorSeriesOper::analySyncHistoryData(SRequestResult stRequestResult)
{
	//生成日志
	SExecLog sDevExecLog;
	sDevExecLog.m_sDevName = m_pDevData->m_sDevName;
	sDevExecLog.m_sFuncName = A2T("历史数据");
	sDevExecLog.m_sDescriptionl = A2T("开始解析历史数据");
	sDevExecLog.m_nAlarmLevel = enWorkInfo;
	CLogOper::instance().addMsg(sDevExecLog);
	if (!stRequestResult.bResult)
	{
		return;
	}
	
	// 将JSON字符串转换为QJsonDocument
	QJsonDocument doc = QJsonDocument::fromJson(stRequestResult.sResult);
	// 检查是否成功解析JSON
	if (!doc.isObject()) 
	{
		return;
	}
	//在数据库中查询一天前的数据,并保存在一个数组中
	QMap<QString, QMap<int,QMap<int,SSensorHisData>>> mapData;
	selectHistoryDataByDB(mapData);

	QJsonObject jsonObj = doc.object();

	if (!jsonObj.contains("SearchResult"))
	{
		return;
	}
	QJsonObject searchResult = jsonObj["SearchResult"].toObject();
	// 访问数据
	if (!searchResult.contains("responseStatusStrg") || !searchResult.contains("numOfMatches") || !searchResult.contains("totalMatches"))
	{
		return;
	}
	QString responseStatus = searchResult["responseStatusStrg"].toString();
	int numOfMatches = searchResult["numOfMatches"].toInt();
	int totalMatches = searchResult["totalMatches"].toInt();

	// 访问ResultList数组
	if (!searchResult.contains("ResultList"))
		return;
	QJsonArray resultList = searchResult["ResultList"].toArray();
	for (const QJsonValue &value : resultList)
	{
		QJsonObject resultObj = value.toObject();
		int nChannel;
		QString sChannelName = "";
		int nDataDirect;//轴向
		int nMatchLevel;//匹配度
		int nResult;//诊断结果
		QString sTime;//采集时间
		QString sTimeDB;//采集时间
		QString sTimeKey;
		double dRMS = 0.0;//加速度
		double dTemp = 0.0;//温度
		QString sRMSFileUrl;//加速度文件
		QString sVoiceFileUrl;//音频文件
		int nTempResult = 0;
		int nRMSResult = 0;
		int nVoiceResult = 0;
		if (resultObj.contains("audioID"))//通道号
		{
			nChannel = resultObj["audioID"].toInt();
			if (!m_pDevData->m_mapChannel.contains(nChannel))
			{
				continue;
			}
			if (m_pDevData->m_mapChannel[nChannel].nIsEnable == 0)//未启用
			{
				continue;
			}
			sChannelName = m_pDevData->m_mapChannel[nChannel].sChannelName;
		}
		if (resultObj.contains("accDirect"))//轴向
		{
			QString sDataDirect = resultObj["accDirect"].toString();
			if (sDataDirect == "x")
			{
				nDataDirect = 1;
			}
			else if (sDataDirect == "y")
			{
				nDataDirect = 2;
			}
			else if (sDataDirect == "z")
			{
				nDataDirect = 3;
			}
		}
		if (resultObj.contains("matchLevel"))//匹配度
		{
			nMatchLevel= resultObj["matchLevel"].toInt();
		}
		if (resultObj.contains("result"))//诊断结果
		{
			QString sResult = resultObj["result"].toString();
			if (sResult == "normal")
			{
				nResult = 0;
			}
			else
			{
				nResult = 1;
			}
		}
		if (resultObj.contains("time"))//采集时间
		{
			QString sCollectTime = resultObj["time"].toString();
			sTimeDB = QDateTime::fromString(sCollectTime, "yyyy-MM-ddTHH:mm:ss+08:00").toString("yyyy/MM/dd HH:mm:ss");
			sTime = QDateTime::fromString(sCollectTime, "yyyy-MM-ddTHH:mm:ss+08:00").toString("yyyyMMddHHmmss");
			sTimeKey = QDateTime::fromString(sCollectTime, "yyyy-MM-ddTHH:mm:ss+08:00").toString("yyyyMMddHHmm");
		}
		if (resultObj.contains("RMS"))//加速度
		{
			dRMS = resultObj["RMS"].toDouble();
		}
		if (resultObj.contains("tempValue"))//温度
		{
			dTemp = resultObj["tempValue"].toDouble();
		}
		if (resultObj.contains("vibFileUrl"))//加速度文件
		{
			sRMSFileUrl = resultObj["vibFileUrl"].toString();
		}
		if (resultObj.contains("audioUrl"))//音频文件
		{
			sVoiceFileUrl = resultObj["audioUrl"].toString();
		}
		if (resultObj.contains("tempResult"))//温度检测结果
		{
			QString sTempResult= resultObj["tempResult"].toString();
			if (sTempResult == "normal")
			{
				nTempResult = 0;
			}
			else
			{
				nTempResult = 1;
			}
		}
		if (resultObj.contains("vibrationResult"))//RMS检测结果
		{
			QString sRMSResult = resultObj["vibrationResult"].toString();
			if (sRMSResult == "normal")
			{
				nRMSResult = 0;
			}
			else
			{
				nRMSResult = 1;
			}
		}
		if (resultObj.contains("voiceprintResult"))//温度检测结果
		{
			QString sVoiceResult = resultObj["voiceprintResult"].toString();
			if (sVoiceResult == "normal")
			{
				nVoiceResult = 0;
			}
			else
			{
				nVoiceResult = 1;
			}
		}
		bool bIsContains = false;
		if (mapData.contains(sTimeKey))//数据库中存在这个时间段内的数据
		{
			QMap<int, QMap<int, SSensorHisData>> mapChannel = mapData[sTimeKey];
			if (mapChannel.contains(nChannel))
			{
				QMap<int, SSensorHisData> mapDirect = mapChannel[nChannel];
				if (mapDirect.contains(nDataDirect))
				{
					bIsContains = true;
				}
				else
				{
					bIsContains = false;
				}
			}
			else
			{
				bIsContains = false;
			}
		}
		else
		{
			bIsContains = false;
		}

		if (bIsContains == false)//数据库中不存在
		{
			//首先获取加速度文件
			QString sAccelerationHttpUrl = g_sHttpUrl + "SensorSeries/RMS/"+ QDateTime::fromString(sTime,"yyyyMMddHHmmss").toString("yyyyMM/")
				+ QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("dd/")+ QString("ch%1_%2_").arg(nChannel).arg(nDataDirect)+sTime+".txt";
			QString sAccelerationPath = g_sPdfOutputPath + "SensorSeries/RMS/" + QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("yyyyMM/")
				+ QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("dd/") + QString("ch%1_%2_").arg(nChannel).arg(nDataDirect) + sTime + ".txt";
			QUrl urlAcceleration(sRMSFileUrl);
			m_pIsapiClient->sendRequestGet(ERequestType::enGetHisAcceleration, sAccelerationPath,urlAcceleration);
			sysSleep(50);
			//获取音频文件
			QString sAudioHttpUrl = g_sHttpUrl + "SensorSeries/Voice/" + QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("yyyyMM/")
				+ QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("dd/") + QString("ch%1_%2_").arg(nChannel).arg(nDataDirect) + sTime + ".wav";
			QString sAudioHttpPath = g_sPdfOutputPath + "SensorSeries/Voice/" + QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("yyyyMM/")
				+ QDateTime::fromString(sTime, "yyyyMMddHHmmss").toString("dd/") + QString("ch%1_%2_").arg(nChannel).arg(nDataDirect) + sTime + ".wav";
			QUrl urlAudio(sVoiceFileUrl);
			m_pIsapiClient->sendRequestGet(ERequestType::enGetHisAudio, sAudioHttpPath,urlAudio);
			//在数据库中添加
			SSensorHisData stData;
			stData.sGuid = createGuid();
			stData.sDevGuid = m_pDevData->m_sDevGuid;
			stData.nChannelNo = nChannel;
			stData.sChannelName = sChannelName;
			stData.nDataDirection = nDataDirect;
			stData.nResult = nResult;
			stData.nTempResult = nTempResult;
			stData.nRMSResult = nRMSResult;
			stData.nVoiceResult = nVoiceResult;
			stData.nMatchLevel = nMatchLevel;
			stData.sTime = sTimeDB;
			stData.dRMS = dRMS;
			stData.dTemp = dTemp;
			stData.sRMSFileUrl = sAccelerationHttpUrl;
			stData.sVoiceFileUrl = sAudioHttpUrl;
			QString sErr = "";
			CSqlOper::instance().addSensorSeriesHistory(stData, sErr);
		}
		else
		{
			continue;
		}
	}
	//最后将没有保存过csv文件和音频文件的保存在本地
	sDevExecLog.m_sDescriptionl = A2T("解析历史数据结束");
	CLogOper::instance().addMsg(sDevExecLog);
}

void CSensorSeriesOper::extractJsonFromMultipart(const QByteArray &rawData)
{
	
}

void CSensorSeriesOper::selectHistoryDataByDB(QMap<QString, QMap<int,QMap<int,SSensorHisData>>>& mapData)
{
	QDateTime currentDateTime = QDateTime::currentDateTime();
	QString sCurrentDateTime = currentDateTime.toString("yyyy/MM/dd HH:mm:ss");
	// 获取一周前的时间
	QDateTime oneWeekAgo = currentDateTime.addDays(-1);
	QString sOneWeekAgo = oneWeekAgo.toString("yyyy/MM/dd HH:mm:ss");
	QVector<QSqlRecord> vecData;
	QString sErrMsg = "";
	CSqlOper::instance().selectHisData(m_pDevData->m_sDevGuid, sOneWeekAgo, sCurrentDateTime, vecData, sErrMsg);
	for (int i = 0; i < vecData.size(); i++)
	{
		SSensorHisData stData;
		stData.sGuid = vecData[i].value("GUID").toString();
		stData.sDevGuid = vecData[i].value("DEV_GUID").toString();
		stData.nChannelNo= vecData[i].value("CHANNEL_NO").toInt();
		stData.nDataDirection = vecData[i].value("DATA_DIRECTION").toInt();
		stData.sTime = vecData[i].value("TIME").toDateTime().toString("yyyy-MM-ddTHH:mm:ss+8:00");
		QString sTimeKey= vecData[i].value("TIME").toDateTime().toString("yyyyMMddHHmm");
		stData.dTemp = vecData[i].value("TEMP").toDouble();
		stData.dRMS = vecData[i].value("RMS").toDouble();
		stData.sRMSFileUrl = vecData[i].value("RMS_FILE_URL").toString();
		stData.sVoiceFileUrl = vecData[i].value("VOICE_FILE_URL").toString();
		// 如果该时间键已经存在，则直接修改内部结构
		if (!mapData.contains(sTimeKey))
		{
			QMap<int, QMap<int, SSensorHisData>> mapChannel;
			mapData.insert(sTimeKey, mapChannel);
		}
		// 获取当前时间键下的通道数据
		QMap<int, QMap<int, SSensorHisData>>& mapChannel = mapData[sTimeKey];

		if (!mapChannel.contains(stData.nChannelNo))
		{
			QMap<int, SSensorHisData> mapDirect;
			mapChannel.insert(stData.nChannelNo, mapDirect);
		}

		// 获取当前通道号下的数据方向数据
		QMap<int, SSensorHisData>& mapDirect = mapChannel[stData.nChannelNo];

		// 插入数据
		mapDirect.insert(stData.nDataDirection, stData);
	}
}

void CSensorSeriesOper::slotResult(int nRequestType, SRequestResult stRequestResult)
{
	switch (nRequestType)
	{
	case ERequestType::enSearchChild:
	{
		analySearchChild(stRequestResult);
		break;
	}
	case ERequestType::enSyncHistoryData:
	{
		analySyncHistoryData(stRequestResult);
		break;
	}
	case ERequestType::enSearchHistoryData:
	{
		analyHistoryData(stRequestResult);
		break;
	}
	case ERequestType::enGetSensorCollectDataFile:
	{
		analyGetSensorCollectDataFile(stRequestResult);
		break;
	}
	case ERequestType::enGetAcceleration:
	{
		analyAccelerationFile(stRequestResult);
		break;
	}
	case ERequestType::enGetAudio:
	{
		analyAudioFile(stRequestResult);
		break;
	}
	default:
		break;
	}
}

void CSensorSeriesOper::slotResultParame(int nRequestType, QString sParame, SRequestResult stRequestResult)
{
	switch (nRequestType)
	{
	case ERequestType::enGetHisAcceleration:
	{
		analyHisAccelerationFile(stRequestResult, sParame);
		break;
	}
	case ERequestType::enGetHisAudio:
	{
		analyHisAudioFile(stRequestResult, sParame);
		break;
	}
	default:
		break;
	}
}

void CSensorSeriesOper::slotNewRequest(QByteArray &requestData)
{
	extractJsonFromMultipart(requestData);
}

void CSensorSeriesOper::handleInternalPostRequest(int requestType, const QUrl& url, const QByteArray& postData)
{
	// 现在这个调用会在正确的线程中执行
	m_pIsapiClient->sendRequestPost(requestType, const_cast<QUrl&>(url), const_cast<QByteArray&>(postData));
}

void CSensorSeriesOper::handleInternalGetRequest(int requestType, const QUrl& url)
{
	m_pIsapiClient->sendRequestGet(requestType, const_cast<QUrl&>(url));
}

void CSensorSeriesOper::handleInternalGetRequestWithParam(int requestType, const QString& param, const QUrl& url)
{
	m_pIsapiClient->sendRequestGet(requestType, param, const_cast<QUrl&>(url));
}
